'use strict';

const Service = require('egg').Service;
const random = require('random');
const uuidv4 = require('uuid/v4');

const randNum = random.int(100000, 999999);

class RegisterUserService extends Service {
  async moiter(tel) {
    const { ctx, app } = this;
    const result = await ctx.model.User.findOne({
      where: {
        tel,
      },
    });
    if (!result) {
      app.redis.setex('regtelcode', 60, randNum);
      app.redis.set('regtel', tel);
      return {
        status: 200,
        randNum,
        msg: '发送短信成功',
      };
    }
    return {
      status: 400,
      msg: '此手机已注册过,请更换手机号重试',
    };
    // ctx.helper.sendCode(tel, randNum);
    // if (result.error_code === 0) {
    //   app.redis.setex('telcode', 60, randNum);
    //   ctx.body = {
    //     status: 200,
    //     msg: '发送短信成功',
    //   };
    // }
  }
  async verifTel(tel_Code) {
    const { ctx, app } = this;
    const redis_tel = await app.redis.get('regtel');
    const redis_Code = await app.redis.get('regtelcode');
    if (tel_Code.tel === parseInt(redis_tel) && tel_Code.Code === redis_Code) {
      ctx.body = {
        status: 200,
        msg: '验证手机号成功',
      };
    } else {
      ctx.body = {
        status: 400,
        msg: '手机号或验证码错误',
      };
    }
  }
  async register(resInfo) {
    const { ctx, app } = this;
    const nickname = uuidv4();
    const tel = await app.redis.get('regtel');
    resInfo.tel = tel;
    resInfo.password = ctx.service.user.getMd5Data(resInfo.pwd);
    resInfo.nickname = nickname.split('-')[0] + '_' + Date.now();
    resInfo.userimg = 'images/user/mw-touxiang.png';
    resInfo.createdDate = new Date();
    resInfo.updatedDate = new Date();
    ctx.logger.debug('>>>>> 请求新增一个用户 <<<<<');
    const result = await ctx.model.User.create({
      password: resInfo.password,
      userimg: resInfo.userimg,
      tel: resInfo.tel,
      nickname: resInfo.nickname,
      sex: resInfo.sex,
      createdDate: resInfo.createdDate,
      updatedDate: resInfo.updatedDate,
    });
    if (result) {
      const userInfo = {
        contact: resInfo.tel,
        password: resInfo.pwd,
      };
      const loginInfo = await ctx.service.user.login(userInfo);
      if (loginInfo.state === 200) {
        return {
          state: 200,
          msg: '注册成功, 5秒后自动登录且跳转首页',
          tokenID: loginInfo.tokenID,
        };
      }
      return {
        status: 400,
        msg: '注册失败, 请重新再试',
      };
    }
    return {
      status: 400,
      msg: '注册失败, 请重新再试',
    };
  }
}

module.exports = RegisterUserService;
